import { FishModeService } from '../services/fishModeService';

class TaskPaneUI {
    private fishModeService: FishModeService;
    
    private elements = {
        statusDot: null as HTMLElement | null,
        statusText: null as HTMLElement | null,
        toggleButton: null as HTMLButtonElement | null,
        progressFill: null as HTMLElement | null,
        progressText: null as HTMLElement | null,
        novelTitle: null as HTMLElement | null,
        novelStats: null as HTMLElement | null,
        fileInput: null as HTMLInputElement | null,
        resetProgress: null as HTMLButtonElement | null,
        clearStorage: null as HTMLButtonElement | null
    };

    constructor() {
        this.fishModeService = FishModeService.getInstance();
        this.bindElements();
        this.attachEventListeners();
        this.updateUI();
        
        // 定期更新UI
        setInterval(() => this.updateUI(), 1000);
    }

    private bindElements(): void {
        this.elements.statusDot = document.getElementById('statusDot');
        this.elements.statusText = document.getElementById('statusText');
        this.elements.toggleButton = document.getElementById('toggleButton') as HTMLButtonElement;
        this.elements.progressFill = document.getElementById('progressFill');
        this.elements.progressText = document.getElementById('progressText');
        this.elements.novelTitle = document.getElementById('novelTitle');
        this.elements.novelStats = document.getElementById('novelStats');
        this.elements.fileInput = document.getElementById('fileInput') as HTMLInputElement;
        this.elements.resetProgress = document.getElementById('resetProgress') as HTMLButtonElement;
        this.elements.clearStorage = document.getElementById('clearStorage') as HTMLButtonElement;
    }

    private attachEventListeners(): void {
        // 切换摸鱼模式
        this.elements.toggleButton?.addEventListener('click', () => {
            this.toggleFishMode();
        });

        // 文件导入
        this.elements.fileInput?.addEventListener('change', (event) => {
            this.handleFileImport(event);
        });

        // 重置进度
        this.elements.resetProgress?.addEventListener('click', () => {
            this.resetProgress();
        });

        // 清除存储
        this.elements.clearStorage?.addEventListener('click', () => {
            this.clearStorage();
        });

        // 监听快捷键
        document.addEventListener('keydown', (event) => {
            if (event.ctrlKey && event.shiftKey && event.key === 'F') {
                event.preventDefault();
                this.toggleFishMode();
            }
        });
    }

    private toggleFishMode(): void {
        const isActive = this.fishModeService.toggleFishMode();
        this.showNotification(
            isActive ? '摸鱼模式已启用 🐠' : '正常模式已启用 📝',
            isActive ? 'success' : 'info'
        );
        this.updateUI();
    }

    private async handleFileImport(event: Event): Promise<void> {
        const input = event.target as HTMLInputElement;
        const file = input.files?.[0];
        
        if (!file) return;

        try {
            const novel = await this.fishModeService.getNovelService().importFromFile(file);
            this.fishModeService.getNovelService().setCurrentNovel(novel.id);
            this.showNotification(`小说 "${novel.title}" 导入成功！`, 'success');
            this.updateUI();
            
            // 清除文件输入
            input.value = '';
        } catch (error) {
            console.error('File import error:', error);
            this.showNotification('文件导入失败，请检查文件格式', 'error');
        }
    }

    private resetProgress(): void {
        this.fishModeService.getNovelService().resetProgress();
        this.showNotification('阅读进度已重置', 'info');
        this.updateUI();
    }

    private clearStorage(): void {
        if (confirm('确定要清除所有数据吗？此操作不可撤销。')) {
            localStorage.clear();
            this.showNotification('所有数据已清除', 'warning');
            // 重新加载默认小说
            this.fishModeService.getNovelService().loadDefaultNovel();
            this.updateUI();
        }
    }

    private updateUI(): void {
        this.updateStatus();
        this.updateProgress();
        this.updateNovelInfo();
    }

    private updateStatus(): void {
        const isActive = this.fishModeService.isFishModeActive();
        
        // 更新状态指示器
        if (this.elements.statusDot) {
            this.elements.statusDot.className = `status-dot ${isActive ? 'active' : 'inactive'}`;
        }

        // 更新状态文本
        if (this.elements.statusText) {
            this.elements.statusText.textContent = isActive ? '摸鱼模式' : '正常模式';
        }

        // 更新按钮
        if (this.elements.toggleButton) {
            this.elements.toggleButton.textContent = isActive ? '关闭摸鱼模式' : '启用摸鱼模式';
            this.elements.toggleButton.className = `toggle-button ${isActive ? 'deactivate' : 'activate'}`;
        }
    }

    private updateProgress(): void {
        const state = this.fishModeService.getState();
        const progress = state.totalCharacters > 0 
            ? (state.readCharacters / state.totalCharacters) * 100 
            : 0;

        // 更新进度条
        if (this.elements.progressFill) {
            this.elements.progressFill.style.width = `${progress}%`;
        }

        // 更新进度文本
        if (this.elements.progressText) {
            this.elements.progressText.textContent = 
                `已读: ${state.readCharacters} / ${state.totalCharacters} 字符 (${progress.toFixed(1)}%)`;
        }
    }

    private updateNovelInfo(): void {
        const currentNovel = this.fishModeService.getNovelService().getCurrentNovel();
        
        if (currentNovel) {
            if (this.elements.novelTitle) {
                this.elements.novelTitle.textContent = currentNovel.title;
            }
            
            if (this.elements.novelStats) {
                const stats = `总长度: ${currentNovel.totalLength} 字符 | 最后阅读: ${new Date(currentNovel.lastReadTime).toLocaleString()}`;
                this.elements.novelStats.textContent = stats;
            }
        } else {
            if (this.elements.novelTitle) {
                this.elements.novelTitle.textContent = '未加载小说';
            }
            
            if (this.elements.novelStats) {
                this.elements.novelStats.textContent = '请导入小说文件';
            }
        }
    }

    private showNotification(message: string, type: 'success' | 'error' | 'info' | 'warning'): void {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 6px;
            color: white;
            font-weight: 600;
            z-index: 1000;
            transform: translateX(400px);
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        `;

        // 设置颜色
        const colors = {
            success: '#28a745',
            error: '#dc3545',
            info: '#17a2b8',
            warning: '#ffc107'
        };
        notification.style.backgroundColor = colors[type];
        notification.textContent = message;

        document.body.appendChild(notification);

        // 动画显示
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 100);

        // 自动隐藏
        setTimeout(() => {
            notification.style.transform = 'translateX(400px)';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }
}

// Office.js 初始化
Office.onReady(async (info) => {
    if (info.host === Office.HostType.Word) {
        try {
            // 初始化摸鱼模式服务
            const fishModeService = FishModeService.getInstance();
            await fishModeService.initialize();
            
            // 初始化UI
            new TaskPaneUI();
            
            console.log('Taskpane initialized successfully');
        } catch (error) {
            console.error('Failed to initialize taskpane:', error);
        }
    }
});